from django.shortcuts import render, get_object_or_404
from django.core.paginator import Paginator
from django.conf import settings
from django.contrib.contenttypes.models import ContentType
from django.db.models import Count
from .models import Blog, BlogType
from read_statistics.utils import read_statistics_once_read


def get_blog_list_common(request, blogs_all_list):
    paginator = Paginator(blogs_all_list, settings.EACH_PAGE_BLOGS_NUMBER)  # 分页器初始化
    page_num = request.GET.get('page', 1)  # GET方法得到url中'？'后的参数字典，再用get得到字典中对应page键的值，即页码；若无page键，返回默认值1
    page_of_blogs = paginator.get_page(page_num)
    current_page_num = page_of_blogs.number  # 获取当前页对象的页码
    # 获取当前页码前后各两页的页码范围
    page_range = list(range(max(current_page_num - 2, 1), current_page_num)) + \
                 list(range(current_page_num, min(paginator.num_pages, current_page_num + 2) + 1))
    # 加上省略页码标记
    if page_range[0] - 1 >= 2:
        page_range.insert(0, '...')
    if paginator.num_pages - page_range[-1] >= 2:
        page_range.append('...')
    # 加上首页和尾页
    if page_range[0] != 1:
        page_range.insert(0, 1)
    if page_range[-1] != paginator.num_pages:
        page_range.append(paginator.num_pages)

    # 获取所有博客分类对应的博客数量
    # 方法一：使用annotate注释
    blog_types_list = BlogType.objects.annotate(blog_count=Count('blog'))
    '''
    方法二：
    blog_types = BlogType.objects.all()  # 先获取所有的博客类型，实例化为博客类型对象
    blog_types_list = []  # 用于存放增加过数量属性的博客类型对象
    for blog_type in blog_types:
        blog_type.blog_count = Blog.objects.filter(blog_type=blog_type).count()  # 筛选出所有符合该类型的博客，使用count()函数统计数量
        blog_types_list.append(blog_type)   # 列表中增加该博客类型对象
    '''

    # 获取日期归档对应的博客数量
    blog_dates = Blog.objects.dates('created_time', 'month', order='DESC')
    blog_dates_dict = {}
    for blog_date in blog_dates:
        blog_count = Blog.objects.filter(created_time__year = blog_date.year,
                                         created_time__month = blog_date.month).count()
        blog_dates_dict[blog_date] = blog_count

    context = {}
    context['blogs'] = page_of_blogs.object_list
    context['page_of_blogs'] = page_of_blogs
    context['page_range'] = page_range
    context['blog_types'] = blog_types_list
    context['blog_dates'] = blog_dates_dict  # 传入{blog_date:blog_count}的形式
    return context

def blog_list(request):
    blogs_all_list = Blog.objects.all()
    context = get_blog_list_common(request, blogs_all_list)
    return render(request, 'blog/blog_list.html', context)

def blog_with_type(request, blog_type_pk):
    blog_type = get_object_or_404(BlogType, pk=blog_type_pk)   # 通过分类类型的主键进行筛选类别对象
    blogs_all_list = Blog.objects.filter(blog_type = blog_type)   # 通过分类类型筛选出所有符合条件的blog对象
    context = get_blog_list_common(request, blogs_all_list)
    context['blog_type'] = blog_type
    return render(request, 'blog/blog_with_type.html', context)

def blog_with_date(request, year, month):
    blogs_all_list = Blog.objects.filter(created_time__year=year, created_time__month=month)  # 通过日期字段中的年月来筛选博客对象
    context = get_blog_list_common(request, blogs_all_list)
    context['blog_with_date'] = '%s年%s月' % (year, month)
    return render(request, 'blog/blog_with_date.html', context)

def blog_detail(request, blog_pk):
    blog = get_object_or_404(Blog, pk=blog_pk)
    read_cookie_key = read_statistics_once_read(request, blog)

    context = {}
    context['previous_blog'] = Blog.objects.filter(created_time__gt=blog.created_time).last()
    context['next_blog'] = Blog.objects.filter(created_time__lt=blog.created_time).first()
    context['blog'] = blog
    response = render(request, 'blog/blog_detail.html', context)  # 响应
    response.set_cookie(read_cookie_key, 'true')  # 阅读cookie标记
    return response